<?php

namespace HuangYi\Rbac\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;

class Rbac
{
    /**
     * Handle the request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param string $slug
     * @return mixed
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     */
    public function handle($request, Closure $next, $slug)
    {
        $user = $request->user();

        list($permissions, $all) = $this->parsePermissions($slug);

        if (! $user || ! $user->hasPermissions($permissions, $all)) {
            throw new HttpException(403, 'Forbidden');
        }

        return $next($request);
    }

    /**
     * Parses permissions.
     *
     * @param string $slug
     * @return array
     */
    protected function parsePermissions($slug)
    {
        $slug = trim($slug, '|&');

        $permissions = explode('|', $slug);
        $all = false;

        if (count($permissions) == 1) {
            $permissions = explode('&', $slug);
            $all = true;
        }

        return [$permissions, $all];
    }
}
